/* Copyright (C) 2008, 2009, 2010 Faindu GmbH, Switzerland.
* All Rights Reserved. The following is Source Code and is subject to all restrictions 
* on such code as contained in the license accompanying this project. */
package blocstac.editimage.zoom
{

import blocstac.editimage.base.StateManager;
import blocstac.editimage.rotate.RotateComponent;

import flash.events.MouseEvent;

/**
 * The user drags these "buttons" to edit the image.
 */
public class PanTool
{
	private var _stateManager:StateManager	
	private var _rotateComponent:RotateComponent
	private var _lastMoveX:Number
	private var _lastMoveY:Number
	
	function PanTool(stateManager:StateManager, rotateComponent:RotateComponent) {
		_stateManager = stateManager
		_rotateComponent = rotateComponent
	}

	//--------------------------------------------------------------------------
	//
	//  Methods
	//
	//--------------------------------------------------------------------------
	public function updateEditState():void {
		if (_stateManager.editState.isZoomable) {
			_rotateComponent.addEventListener(MouseEvent.MOUSE_DOWN, dragMaskHandler)
		} else {
			_rotateComponent.removeEventListener(MouseEvent.MOUSE_DOWN, dragMaskHandler)
		}
	}
	
	private function dragMaskHandler(mouseEvent:MouseEvent):void {
		if (_stateManager.viewModel.userViewIsScaled()) {
			_rotateComponent.addEventListener(MouseEvent.MOUSE_UP, stopDragginHandler, false, 10)
			_rotateComponent.addEventListener(MouseEvent.MOUSE_OUT, stopDragginHandler, false, 10)
			_rotateComponent.addEventListener(MouseEvent.MOUSE_MOVE, moveMaskHandler, false, 10)
			_lastMoveX = mouseEvent.localX
			_lastMoveY = mouseEvent.localY
		}
	}
	
	private function moveMaskHandler(mouseEvent:MouseEvent):void {
		var relativeMoveX:Number = mouseEvent.localX - _lastMoveX
		var relativeMoveY:Number = mouseEvent.localY - _lastMoveY
		
		_stateManager.applyPan(relativeMoveX, relativeMoveY)
		
		_lastMoveX = mouseEvent.localX
		_lastMoveY = mouseEvent.localY
		_rotateComponent.dispatchEvent(new ZoomOrPanEvent())
		mouseEvent.stopImmediatePropagation()
	}
	
	private function stopDragginHandler(mouseEvent:MouseEvent):void {
		_rotateComponent.removeEventListener(MouseEvent.MOUSE_UP, stopDragginHandler)
		_rotateComponent.removeEventListener(MouseEvent.MOUSE_OUT, stopDragginHandler)
		_rotateComponent.removeEventListener(MouseEvent.MOUSE_MOVE, moveMaskHandler)
		mouseEvent.stopImmediatePropagation()
	}
	
}
}